package com.domor.web.controller.system;

import com.domor.common.annotation.Log;
import com.domor.common.core.controller.BaseController;
import com.domor.common.core.domain.AjaxResult;
import com.domor.common.core.page.TableDataInfo;
import com.domor.framework.shiro.util.ShiroUtils;
import com.domor.system.domain.SysRole;
import com.domor.system.domain.SysUser;
import com.domor.system.service.SysRoleService;
import com.domor.system.service.SysUserService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <h3>角色管理控制层</h3>
 *
 * @author liyuyang
 * @date 2020/4/22
 **/
@Controller
@RequestMapping("/system/role")
public class SysRoleController extends BaseController {

    private String prefix = "system/role";

    @Autowired
    private SysRoleService roleService;

    @Autowired
    private SysUserService userService;

    /**
     * 角色管理-首页
     */
    @GetMapping()
    public String index() {
        return prefix + "/index";
    }

    /**
     * 角色管理-首页列表查询
     *
     * @param role
     */
    @RequiresPermissions("system:role:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(SysRole role) {
        setOrderByAndPage();
        List<SysRole> list = roleService.selectRoleList(role);
        return getDataTable(list);
    }

    /**
     * 角色下拉列表
     */
    @PostMapping("/getRoles")
    @ResponseBody
    public Object getRoles() {
        SysRole role = new SysRole();
        List<SysRole> list = roleService.selectRoleList(role);
        return list;
    }

    /**
     * 新增角色
     */
    @GetMapping("/add")
    public String add() {
        return prefix + "/add";
    }

    /**
     * 新增保存角色
     */
    @RequiresPermissions("system:role:add")
    @Log(title = "角色管理")
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(@Validated SysRole role) {
        if (roleService.checkRoleNameUnique(role) > 0) {
            return error("新增角色'" + role.getRoleName() + "'失败，角色名称已存在");
        } else if (roleService.checkRoleKeyUnique(role) > 0) {
            return error("新增角色'" + role.getRoleName() + "'失败，角色权限已存在");
        }
        role.setCreateBy(ShiroUtils.getLoginName());
        return toAjax(roleService.insertRole(role));
    }

    /**
     * 修改角色
     */
    @GetMapping("/edit/{roleId}")
    public String edit(@PathVariable("roleId") Long roleId, ModelMap mmap) {
        mmap.put("role", roleService.selectRoleById(roleId));
        return prefix + "/edit";
    }

    /**
     * 修改保存角色
     */
    @RequiresPermissions("system:role:edit")
    @Log(title = "角色管理")
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(@Validated SysRole role) {
        roleService.checkRoleAllowed(role);
        if (roleService.checkRoleNameUnique(role) > 0) {
            return error("修改角色'" + role.getRoleName() + "'失败，角色名称已存在");
        } else if (roleService.checkRoleKeyUnique(role) > 0) {
            return error("修改角色'" + role.getRoleName() + "'失败，角色权限已存在");
        }
        role.setUpdateBy(ShiroUtils.getLoginName());
        return toAjax(roleService.updateRole(role));
    }

    /**
     * 保存角色分配菜单权限
     */
    @RequiresPermissions("system:role:auth")
    @Log(title = "角色管理：保存权限")
    @PostMapping("/saveRoleMenus")
    @ResponseBody
    public AjaxResult saveRoleMenus(SysRole role) {
        role.setUpdateBy(ShiroUtils.getLoginName());
        ShiroUtils.clearCachedAuthorizationInfo();
        return toAjax(roleService.saveRoleMenu(role));
    }

    /**
     * 角色分配数据权限
     */
    @GetMapping("/authDataScope/{roleId}")
    public String authDataScope(@PathVariable("roleId") Long roleId, ModelMap mmap) {
        mmap.put("role", roleService.selectRoleById(roleId));
        return prefix + "/dataScope";
    }

    /**
     * 保存角色分配数据权限
     */
    @RequiresPermissions("system:role:edit")
    @Log(title = "角色管理")
    @PostMapping("/authDataScope")
    @ResponseBody
    public AjaxResult authDataScopeSave(SysRole role) {
        roleService.checkRoleAllowed(role);
        role.setUpdateBy(ShiroUtils.getLoginName());
        if (roleService.authDataScope(role) > 0) {
            SysUser newUser = userService.selectUserById(ShiroUtils.getUserId());
            ShiroUtils.setSysUser(newUser);
            return success();
        }
        return error();
    }

    @RequiresPermissions("system:role:delete")
    @Log(title = "角色管理")
    @PostMapping("/delete/{roleId}")
    @ResponseBody
    public AjaxResult delete(@PathVariable Long roleId) {
        try {
            return toAjax(roleService.deleteRoleById(roleId));
        } catch (Exception e) {
            return error(e.getMessage());
        }
    }

}